<script setup lang="ts">
import { Swiper, SwiperSlide } from 'swiper/vue'
import { EffectCoverflow, Pagination, Autoplay } from 'swiper/modules'
import 'swiper/css'

onActivated(async () => {
  const { query } = useRoute()
  refPage.value.scrollTop = scrollTop.value
  console.log(query)

  if (query?.sp) {
    const devStore = localStorage.getItem('chinfo') ?? `{}`
    const devInfo = JSON.parse(devStore)
    devInfo.code = query.sp
    localStorage.setItem('chinfo', JSON.stringify(devInfo))
    shareSecond()
  }

  await getBanners()
  await getCategories()
})
onBeforeRouteLeave(() => {
  scrollTop.value = refPage.value.scrollTop
})

/* common vars */
const refPage = ref()
const scrollTop = ref(0)
const router = useRouter()
const { sourceCdnUrl } = useRuntimeConfig().public
const coverflowEffect = {
  rotate: 0,
  stretch: 10,
  depth: 100,
  modifier: 2,
}

// 第二版分享链接
async function shareSecond() {
  const { Data: linkInfo } = await useRequest.post('/GetLinkDetail')
  const urlFid = Number(linkInfo.film_id)
  const urlEpid = Number(linkInfo.film_episode_no)
  const deviceInfo = {
    ch: linkInfo.channel_no,
    zch: linkInfo.channel_no,
    code: linkInfo.code,
  }
  localStorage.setItem('chinfo', JSON.stringify(deviceInfo))
  await useRequest.post('/LinkClick')
  return { urlFid, urlEpid }
}

/* banners list */
const bannerList = ref<any[]>([])
async function getBanners() {
  const { Data } = await useRequest.post('GetBanner')
  const dataList = Data ?? []
  dataList.sort((a: any, b: any) => b.weight - a.weight)
  bannerList.value = dataList
}

/* get movie list */
async function getMovieByCategoryId(params: any) {
  const { Data } = await useRequest.post('/GetFilmList', params)
  return Data?.list ?? []
}

/* movies category */
const categoryList = ref<any[]>([])
async function getCategories() {
  const { Data } = await useRequest.post('/GetFilmCategoryList')
  const dataList = (Array.isArray(Data) ? Data : []).map((item: any) => {
    return {
      film_category_id: item.id,
      page_index: 1,
      page_size: 10,
      name: item.name,
    }
  })
  for (let i = 0; i < dataList.length; i++) {
    const item: any = dataList[i]
    item.movieList = await getMovieByCategoryId(dataList[i])
  }
  categoryList.value = dataList
}

/* click movie */
function onClickMovie(item: any) {
  router.push({
    path: '/player',
    query: {
      fid: useRequest.encrypt(String(item.id)),
    },
  })
}

async function onTransitionEnd(e: any, item: any, index: number) {
  if (e.virtualSize + e.translate - e.width < 500) {
    item.page_index++
    const param = {
      film_category_id: item.film_category_id,
      page_index: item.page_index,
      page_size: 10,
      name: item.name,
    }
    const list = await getMovieByCategoryId(param)
    item.movieList = item.movieList.concat(list || [])
    categoryList.value.splice(index, 1, item)
  }
}
</script>

<template>
  <div
    ref="refPage"
    class="page">
    <!-- nav-bar -->
    <NavBar
      :show-logo="true"
      :show-nav-right="true">
    </NavBar>

    <div class="page-container">
      <!-- banner -->
      <section class="swiper-section">
        <swiper
          effect="coverflow"
          :centered-slides="true"
          :slides-per-view="3"
          :space-between="70"
          :autoplay="{ delay: 3000 }"
          :coverflow-effect="coverflowEffect"
          :pagination="{ el: '.swiper-pagination' }"
          :modules="[EffectCoverflow, Pagination, Autoplay]">
          <swiper-slide
            v-for="(bannerItem, index) in bannerList"
            :key="index">
            <img
              v-lazy="`${sourceCdnUrl}${bannerItem.image}`"
              class="banner-img"
              :alt="bannerItem" />

            <div
              class="play-btn"
              @click.stop="onClickMovie(bannerItem)">
              <svg-icon name="play-black"></svg-icon>
              play
            </div>
          </swiper-slide>
        </swiper>
        <div class="swiper-pagination"></div>
      </section>

      <!-- movie-section -->
      <section
        v-for="(item, index) in categoryList"
        :key="item.id"
        class="movie-section">
        <h2 class="movie-category">{{ item.name }}</h2>
        <swiper
          :slides-per-view="2.5"
          :space-between="30"
          :free-mode="true"
          :slides-offset-after="20"
          :autoplay="{ delay: 3000 }"
          @slide-next-transition-end="e => onTransitionEnd(e, item, index)">
          <swiper-slide
            v-for="(movieItem, mvIndex) in item?.movieList"
            :key="mvIndex">
            <div class="movie-item">
              <img
                v-lazy="`${sourceCdnUrl}${movieItem.image}`"
                class="movie-img"
                :alt="movieItem.img"
                @click="onClickMovie(movieItem)" />
            </div>
            <div class="movie-name">{{ movieItem?.name }}</div>
          </swiper-slide>
        </swiper>
      </section>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.page {
  overflow-y: auto;
}
.page-container {
  padding: 66px 0 20px;
  .swiper-section {
    overflow: hidden;
    .swiper {
      position: relative;
      width: 1060px;
      left: 50%;
      transform: translateX(-50%);
      .swiper-slide {
        position: relative;
        height: 376px;
        width: 100%;
        border-radius: 12px;
        overflow: hidden;
        .banner-img {
          height: 100%;
          width: 100%;
        }
        .play-btn {
          @include flexbox($jc: center, $ai: center);
          position: absolute;
          bottom: 14px;
          left: 50%;
          width: 110px;
          height: 32px;
          background: #f5f5f5;
          border-radius: 6px;
          transform: translateX(-50%);
          color: #222;
          cursor: pointer;
          .svg-icon {
            margin-right: 8px;
          }
        }
      }
    }
    margin-bottom: 27px;
  }
  .movie-section {
    padding: 0 14px;
    margin-bottom: 18px;
    min-height: 188px;
    &:last-child {
      margin-bottom: 0;
    }
    .movie-category {
      font-size: 14px;
      font-weight: 600;
      color: #fff;
      margin-bottom: 8px;
    }
    .movie-item {
      width: 142px;
      height: 188px;
      cursor: pointer;
      .movie-img {
        width: 100%;
        height: 100%;
      }
    }
    .movie-name {
      font-size: 13px;
      margin-top: 10px;
      line-height: 16px;
      @include ellipsis(2);
    }
  }
}
</style>

<style lang="scss">
.swiper-pagination {
  @include flexbox($jc: center, $ai: center);
  padding-top: 17px;
  .swiper-pagination-bullet {
    display: block;
    width: 12px;
    height: 2px;
    background-color: #999;
    margin-right: 3px;
    &:last-child {
      margin-right: 0;
    }
    &-active {
      background-color: #f5f5f5;
    }
  }
}
</style>
